package controllers

import (
	"encoding/json"
	"strconv"
	"supershare/backend/models"
	"time"

	"github.com/beego/beego/v2/server/web"
)

// DeviceController 设备控制器
type DeviceController struct {
	web.Controller
}

// List 获取设备列表
func (c *DeviceController) List() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取分页参数
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("pageSize", 10)

	// 获取过滤参数
	filters := make(map[string]interface{})

	// 加盟商管理员只能查看自己加盟商的数据
	if permResult.Admin.FranchiseId > 0 {
		// 查询该加盟商下的所有门店ID
		storeIds, err := models.GetStoreIdsByFranchiseId(permResult.Admin.FranchiseId)
		if err == nil && len(storeIds) > 0 {
			filters["store_ids"] = storeIds
		} else {
			// 如果没有门店，则返回空结果
			c.Data["json"] = map[string]interface{}{
				"success": true,
				"data": map[string]interface{}{
					"data":  []*models.Device{},
					"total": 0,
				},
				"page":     page,
				"pageSize": pageSize,
			}
			c.ServeJSON()
			return
		}
	}

	// 门店ID过滤
	storeIdStr := c.GetString("store_id")
	if storeIdStr != "" {
		storeId, err := strconv.ParseInt(storeIdStr, 10, 64)
		if err == nil {
			// 如果是加盟商管理员，需要验证该门店是否属于该加盟商
			if permResult.Admin.FranchiseId > 0 {
				store, err := models.GetStoreById(storeId)
				if err != nil || store == nil || store.FranchiseId != permResult.Admin.FranchiseId {
					c.Data["json"] = map[string]interface{}{
						"success": false,
						"message": "无权访问该门店的设备",
					}
					c.ServeJSON()
					return
				}
			}
			filters["store_id"] = storeId
		}
	}

	// 设备类型过滤
	deviceTypeStr := c.GetString("device_type")
	if deviceTypeStr != "" {
		deviceType, err := strconv.ParseInt(deviceTypeStr, 10, 64)
		if err == nil {
			filters["device_type"] = int8(deviceType)
		}
	}

	// 状态过滤
	statusStr := c.GetString("status")
	if statusStr != "" {
		status, err := strconv.ParseInt(statusStr, 10, 64)
		if err == nil {
			filters["status"] = int8(status)
		}
	}

	// 关键字搜索
	keyword := c.GetString("keyword")
	if keyword != "" {
		filters["keyword"] = keyword
	}

	// 获取设备列表
	devices, total, err := models.GetDeviceList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取设备列表失败",
			"error":   err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"data": map[string]interface{}{
			"data":  devices,
			"total": total,
		},
		"page":     page,
		"pageSize": pageSize,
	}
	c.ServeJSON()
}

// Detail 获取设备详情
func (c *DeviceController) Detail() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取设备ID
	idStr := c.GetString("id")
	if idStr == "" {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "设备ID不能为空",
		}
		c.ServeJSON()
		return
	}

	// 转换ID为整数
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的设备ID",
		}
		c.ServeJSON()
		return
	}

	// 获取设备信息
	device, err := models.GetDeviceById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取设备信息失败",
			"error":   err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if permResult.Admin.FranchiseId > 0 {
		// 获取设备所属的门店
		store, err := models.GetStoreById(device.StoreId)
		if err != nil || store == nil || store.FranchiseId != permResult.Admin.FranchiseId {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "无权访问该设备",
			}
			c.ServeJSON()
			return
		}
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"data":    device,
	}
	c.ServeJSON()
}

// Create 创建设备
func (c *DeviceController) Create() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求数据
	device := new(models.Device)
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, device); err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "解析请求数据失败",
			"error":   err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 验证门店权限
	if permResult.Admin.FranchiseId > 0 {
		// 获取设备所属的门店
		store, err := models.GetStoreById(device.StoreId)
		if err != nil || store == nil || store.FranchiseId != permResult.Admin.FranchiseId {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "无权在该门店创建设备",
			}
			c.ServeJSON()
			return
		}
	}

	// 设置创建者信息
	device.CreatedBy = permResult.Admin.Username
	device.UpdatedBy = permResult.Admin.Username

	// 创建设备
	id, err := models.CreateDevice(device)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建设备失败",
			"error":   err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "创建设备成功",
		"id":      id,
	}
	c.ServeJSON()
}

// Update 更新设备
func (c *DeviceController) Update() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求数据
	device := new(models.Device)
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, device); err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "解析请求数据失败",
			"error":   err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 检查设备ID
	if device.Id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "设备ID不能为空",
		}
		c.ServeJSON()
		return
	}

	// 获取原设备信息
	originalDevice, err := models.GetDeviceById(device.Id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取设备信息失败",
			"error":   err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if permResult.Admin.FranchiseId > 0 {
		// 获取原设备所属的门店
		store, err := models.GetStoreById(originalDevice.StoreId)
		if err != nil || store == nil || store.FranchiseId != permResult.Admin.FranchiseId {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "无权修改该设备",
			}
			c.ServeJSON()
			return
		}

		// 如果修改了门店，需要验证新门店是否属于该加盟商
		if device.StoreId != originalDevice.StoreId {
			newStore, err := models.GetStoreById(device.StoreId)
			if err != nil || newStore == nil || newStore.FranchiseId != permResult.Admin.FranchiseId {
				c.Data["json"] = map[string]interface{}{
					"success": false,
					"message": "无权将设备分配到该门店",
				}
				c.ServeJSON()
				return
			}
		}
	}

	// 设置更新者信息
	device.UpdatedBy = permResult.Admin.Username
	device.UpdatedAt = time.Now().Unix()

	// 更新设备信息
	err = models.UpdateDevice(device)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "更新设备失败",
			"error":   err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "更新设备成功",
	}
	c.ServeJSON()
}

// Delete 删除设备
func (c *DeviceController) Delete() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取设备ID
	idStr := c.GetString("id")
	if idStr == "" {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "设备ID不能为空",
		}
		c.ServeJSON()
		return
	}

	// 转换ID为整数
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的设备ID",
		}
		c.ServeJSON()
		return
	}

	// 获取设备信息
	device, err := models.GetDeviceById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取设备信息失败",
			"error":   err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if permResult.Admin.FranchiseId > 0 {
		// 获取设备所属的门店
		store, err := models.GetStoreById(device.StoreId)
		if err != nil || store == nil || store.FranchiseId != permResult.Admin.FranchiseId {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "无权删除该设备",
			}
			c.ServeJSON()
			return
		}
	}

	// 删除设备
	err = models.DeleteDevice(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "删除设备失败",
			"error":   err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "删除设备成功",
	}
	c.ServeJSON()
}

// UpdateStatus 更新设备状态
func (c *DeviceController) UpdateStatus() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求数据
	var requestData map[string]interface{}
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestData); err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "解析请求数据失败",
			"error":   err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 获取设备ID
	idFloat, ok := requestData["id"].(float64)
	if !ok {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "设备ID不能为空",
		}
		c.ServeJSON()
		return
	}
	id := int64(idFloat)

	// 获取状态
	statusFloat, ok := requestData["status"].(float64)
	if !ok {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "状态不能为空",
		}
		c.ServeJSON()
		return
	}
	status := int8(statusFloat)

	// 获取设备信息
	device, err := models.GetDeviceById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取设备信息失败",
			"error":   err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if permResult.Admin.FranchiseId > 0 {
		// 获取设备所属的门店
		store, err := models.GetStoreById(device.StoreId)
		if err != nil || store == nil || store.FranchiseId != permResult.Admin.FranchiseId {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "无权操作该设备",
			}
			c.ServeJSON()
			return
		}
	}

	// 更新设备状态
	err = models.UpdateDeviceStatus(id, status)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "更新设备状态失败",
			"error":   err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "更新设备状态成功",
	}
	c.ServeJSON()
}
